package com.baby.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSONObject;
import com.baby.feign.FeignClients;
import com.youyicloud.po.WechatPayInfo;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class WeChatService {

	@Autowired
	private RestTemplate restTemplate;
	@Value("${appId}")
	private String appId;
	@Value("${appSecret}")
	private String appSecret;
	@Autowired
	private FeignClients feignClients;
	
	
	public String getAccessToken() {
		String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appId}&secret={appSecret}";
		Map<String,Object> urlVariables = new HashMap<String,Object>();
		urlVariables.put("appId", appId);
		urlVariables.put("appSecret", appSecret);
		ResponseEntity<String> responseEntity =restTemplate.getForEntity(url, String.class, urlVariables);
		JSONObject obj = JSONObject.parseObject(responseEntity.getBody());
        String access_token = obj.getString("access_token");
		return access_token;
	}
	
	public String getTicket(String accessToken) {
		String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+accessToken+"&type=jsapi";
		ResponseEntity<String> responseEntity =restTemplate.getForEntity(url, String.class);
		log.info("jsapi_ticket:{}",responseEntity.getBody());
		JSONObject obj = JSONObject.parseObject(responseEntity.getBody());
        String jsapi_ticket = obj.getString("ticket");
		return jsapi_ticket;
	}
	
	
	/**
	 * 保存微信支付统一下单信息
	 */
	public void saveWechatPay(WechatPayInfo wechatPayInfo) {
		//feignClients.saveWechatPay(wechatPayInfo);
	}
	
	
	/**
	 * 查询微信支付统一下单信息
	 */
	public WechatPayInfo findByMchIdAndOutTradeNo(String mchId,String outTradeNo) {
		List<WechatPayInfo> wechatPayInfos = null;//feignClients.findByMchIdAndOutTradeNo(mchId, outTradeNo);
		if(wechatPayInfos!=null && wechatPayInfos.size()>0) {
			return wechatPayInfos.get(0);
		}
		return null;
	}
	
	
}
